package com.pactera.demo.common.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.pactera.demo.security.config.JwtProperties;
import lombok.Data;

import java.util.Date;

/**
 * <p>
 * JWT生成与校验工具类
 * </p>
 *
 * @author chang.zhou
 * @version 1.0
 * @date Created in 2020/2/29 20:58
 */
@Data
public class JwtTool {

    private static final String CLAIM_NAME = "uid";

    public static String createToken(String userId,String password){
        JwtProperties jwtProperties = SpringContextUtil.getBean(JwtProperties.class);
        Date date = new Date(jwtProperties.getTokenExpiredTime() * 1000 + System.currentTimeMillis());
        Algorithm algorithm = Algorithm.HMAC256(password);
        return JWT.create()
                .withClaim(CLAIM_NAME, userId)
                .withExpiresAt(date)
                .sign(algorithm);
    }

    public static String getClaim(String token){
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(CLAIM_NAME).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static boolean verify(String userId,String password,String token) {
        Algorithm algorithm = Algorithm.HMAC256(password);
        JWTVerifier jwtVerifier = JWT.require(algorithm)
                .withClaim(CLAIM_NAME, userId).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            return false;
        }
        return true;
    }
}
